﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DataBaseReverseGenerator.DataBaseModelGenerator;
using DataBaseReverseGenerator.DataBaseModel;

namespace DataBaseModelGeneratorApp
{
    public partial class Form1 : Form
    {
        private DataBase dbModel;

        public Form1()
        {
            InitializeComponent();
        }

        #region Load

        private void Form1_Load(object sender, EventArgs e)
        {
            // Prompt the user for database link properties dialog
            MSDASC.DataLinksClass dataLinkPropWin = new MSDASC.DataLinksClass();
            ADODB.ConnectionClass dbConn = new ADODB.ConnectionClass();
            dbConn.ConnectionString = "Provider=SQLOLEDB.1";
            object oConn = dbConn;

            if (dataLinkPropWin.PromptEdit(ref oConn))
            {
                DataBaseExplorer dbReverseGen = new DataBaseExplorer(dbConn.ConnectionString);
                dbReverseGen.Explore();
                this.dbModel = dbReverseGen.DbModel;

                DataBindDbObjects();
            }
        }

        #endregion

        #region DataBind

        private void DataBindDbObjects()
        {
            twDbObjects.Nodes.Clear();
            TreeNode rootTableNode = twDbObjects.Nodes.Add("Tables");

            foreach (Table t in this.dbModel.Tables)
            {
                List<TreeNode> tnColumns = new List<TreeNode>();
                foreach (Column col in t.Columns.FindAll(delegate(Column c) { return t.PrimaryKeys.Contains(c.Name); }))
                {
                    string text = String.Format("{0} ({1},{2})", col.Name, col.Type, col.Size);
                    TreeNode tn = new TreeNode(text, 2, 2);
                    tn.Tag = col;
                    tnColumns.Add(tn);
                }
                foreach (Column col in t.Columns.FindAll(delegate(Column c) { return !t.PrimaryKeys.Contains(c.Name); }))
                {
                    string text = String.Format("{0} ({1},{2})", col.Name, col.Type, col.Size);
                    TreeNode tn = new TreeNode(text, 1, 1);
                    tn.Tag = col;
                    tnColumns.Add(tn);
                }

                TreeNode tnTbl = new TreeNode(t.Name, 0, 0, tnColumns.ToArray());
                tnTbl.Tag = t;
                rootTableNode.Nodes.Add(tnTbl);    
            }
        }

        #endregion

        #region Cancel

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion
    }
}